package com.lw.server;

import com.lw.common.Message;
import com.lw.common.MessageType;
import com.lw.common.User;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;

/**
 * 服务端，监听9999端口，等待客户端连接
 */
public class QQServer {

    private ServerSocket serverSocket;

    /**
     * 合法的用户，模拟数据库中保存的用户数据
     */
    private static HashMap<String,User> validUsers = new HashMap<>();
    static {
        validUsers.put("100",new User("100","123"));
        validUsers.put("101",new User("101","123"));
        validUsers.put("102",new User("102","123"));
        validUsers.put("103",new User("103","123"));
    }

    public QQServer(){
        try {
            new Thread(new SendNewsToAllService()).start();//启动推送服务线程

            serverSocket = new ServerSocket(9999);
            System.out.println("服务器启动完毕，端口：9999");
            while (true){//让多个客户连接，用死循环
                Socket socket = serverSocket.accept();//没有客户端连接会阻塞
                ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
                Object obj = inputStream.readObject();

                Message msg = new Message();
                msg.setMsgType(MessageType.MESSAGE_LOGIN_FAIL);

                ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());

                if(obj instanceof User user){
                    //登录验证
                    if(checkUser(user.getUserId(), user.getPasswd())){
                        System.out.println("用户："+user.getUserId()+"登录成功");
                        msg.setMsgType(MessageType.MESSAGE_LOGIN_SUCCESSED);

                        //登录成功，创建线程，保持和客户端的通信
                        ServerConnectClientThread serverConnectClientThread = new ServerConnectClientThread(socket, user.getUserId());
                        serverConnectClientThread.start();

                        //线程放入线程池中进行管理
                        ManageClientThread.addClientThread(user.getUserId(), serverConnectClientThread);
                    }
                }
                outputStream.writeObject(msg);
                if(!msg.getMsgType().equals(MessageType.MESSAGE_LOGIN_SUCCESSED)){//登录失败关闭socket连接
                    socket.close();
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }finally {//当退出了while循环，说明不再需要监听客户端连接，服务器也应该退出
            try {
                serverSocket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 验证用户是否合理
     * @param userId
     * @param pwd
     * @return
     */
    private boolean checkUser(String userId,String pwd){
        User user = validUsers.get(userId);
        if(user!=null&&user.getPasswd().equals(pwd)){
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        new QQServer();
    }
}
